<?php
!defined ('P_W') && exit('Forbidden');
require_once R_P.'mode/house/lib/db/BaseDB.php';
/**
 * @author yishuo  2010-1-23
 * 
 */
class PW_EvaluationDB extends PW_BaseDB{
	var $_tablename = "pw_house_evaluations";
	var $house_score = array('1' => '交通','2' => '环境','3' => '规划','4' => '配套','5' => '开发商');
	var $fullScore = 100;
	var $_ctype = array('evaluation'=>'evaluation','score'=>'score');
	
	function __construct(){
		global $house_field;
		$this->house_score = & $house_field['score'];
		parent::__construct();
	}
	
	/**
	 * @param $conditions	array('key'=>array('value','type'));
	 * @param $page
	 * @param $f
	 * @return unknown_type
	 */
	function searchHouseEvaluation($conditions,$page='all',$f = 'front',$totalCount=false){
		global $house_evaluation_check, $windid;
		$result = array();
		$count = 0;
		$_where = $_sql = $_search = $_limit = '';
		if ($house_evaluation_check && $f == 'front') {
			$_where .= " AND c.ifcheck='1'";
		}
		$_where .= $this->getSqlWhere($conditions,'c');
		$_limit = '';
		if ($page != 'all') {
			$_sql = "SELECT count(*) FROM ".$this->_tablename." c WHERE c.ctype = ".pwEscape($this->_ctype['evaluation'])." $_where";
			$count = $this->_db->get_value($_sql);
			list($result ['pages'],$_limit) = $this->_getPages((int)$count,$page);
			if ($totalCount) $result['totalCount'] = $count;
		} else {
			$_limit = " LIMIT 0,".$this->db_perpage;
		}
		$_sql = "SELECT c.*,m.username,m.icon FROM ".$this->_tablename." c LEFT JOIN pw_members m ON c.uid = m.uid WHERE c.ctype = ".pwEscape($this->_ctype['evaluation'])." $_where ORDER BY c.id DESC $_limit";
		$query = $this->_db->query($_sql);
		while ($rt = $this->_db->fetch_array($query)) {
			$rt['ctime'] =  get_date($rt['ctime']);
			if (!function_exists('showfacedesign')) {
				require_once R_P.'require/showimg.php';
			}
			list($rt['icon']) = showfacedesign($rt["icon"],1,'s');
			!$rt['username'] && $rt['username'] = "游客";
			$rt['subContent'] = substr($rt['content'],0,50);
			if (strlen($rt['content']) > 50) {
				$rt['subContent'] .= '...';
				$rt['sub'] = 'y';
			}
			$result['contents'][] = $rt;
		}
		return $result;
	}
	
	
	/**
	 * @param $id				 
	 * @param $check			 
	 * @return unknown_type
	 */
	function checkHouseEvaluationsById($id,$check){
		!is_array($id) && $id = array($id);
		$check = $check == 'y' ? '1' : '0';
		if (is_array($id) && !empty($id) && in_array($check,array('0','1'))) {
			$_sql = "UPDATE ".$this->_tablename." SET ifcheck=".pwEscape($check)." WHERE id IN (".pwImplode($id).")";
			$this->_db->update($_sql);
		}
	}
	
	/**
	 * @param $data	array
	 * @return null
	 */
	function insertHouseEvaluations($data){
		if (is_array($data) && !empty($data)) {
			$_sql = "INSERT INTO ".$this->_tablename." (uid, hid, hname, ctime, ctype, content, ifcheck) VALUES ".pwSqlMulti($data);
			$this->_db->update($_sql);
			$hids = array();
			foreach ($data as $key => $value) {
				$hids[] = $value[1];
			}
			$this->updateHouseEvaluationsCountByHid($hids);
		}
	}
	
	/**
	 * 获取楼盘评价总数
	 * @param int $hid 楼盘ID
	 * @param bool $ifcheck 是否通过审核
	 */
	function getEvaluationCountByHid($hid,$ifcheck=false){
		$_where = ($ifcheck == true) ? 'ifcheck=1' : 1;		
		$_sql = "SELECT count(*) FROM ".$this->_tablename." WHERE $_where";
		return $this->_db->get_value($_sql);		
	}
	
	/**
	 * 更新楼盘评分数
	 * @param $hid array
	 * @return unknown_type
	 */
	function updateHouseEvaluationsCountByHid($hid){
		if (is_array($hid) && !empty($hid)) {
			$_sql = "UPDATE pw_house_info SET postnum = postnum + 1 WHERE hid IN (".pwImplode($hid).")";
			$this->_db->update($_sql);
		}
	}
	
	/**
	 * @param $hid
	 * @param $score
	 * @return unknown_type
	 */
	function updateHouseEvaluationsScoreByHid($hid,$score){
		if ($hid && is_numeric($hid) && is_numeric($score)) {
			$_sql = "UPDATE pw_house_info SET score=".pwEscape($score)." WHERE hid=".pwEscape($hid);
			$this->_db->update($_sql);
		}
	}
	
	/**
	 * @param $id	评论ID	支持int array
	 * @return null
	 */
	function deleteHouseEvaluationsByID($id,$hid=''){
		is_numeric($id) && $id = array($id);
		if (is_array($id) && !empty($id)) {
			$_sql = "DELETE FROM ".$this->_tablename." WHERE id IN (".pwImplode($id).")";
			$this->_db->update($_sql);
			if ($hid) {
				$_sql = "UPDATE pw_house_info SET postnum = postnum - ".count($id)." WHERE hid=".pwEscape($hid);
				$this->_db->update($_sql);
			}
		}
	}
	
	
	/**
	 * @param $hdata	楼盘信息更新时调用此方法$hdata=array(hid=>hname);
	 * @return null
	 */
	function updateHouseEvaluations($hdata){
		if (is_array($hdata) && !empty($hdata)) {
			foreach ($hdata as $key => $value) {
				$_sql = "UPDATE SET hname=".pwEscape($value)." WHERE id=".pwEscape($key);
				$this->_db->update($_sql);
			}
		}
	}
	
	//评分相关
	/**
	 * 根据后盘ID获取楼盘相关评分信息
	 * @param $hid
	 * @return unknown_type
	 */
	function getScoreByHid($hid){
		$result = array();
		if ($hid && is_numeric($hid)) {
			$_sql = "SELECT c.* FROM ".$this->_tablename." c WHERE c.ctype = ".pwEscape($this->_ctype['score'])." AND c.hid=".pwEscape($hid);
			$rt = $this->_db->get_one($_sql);
			if ($rt) {
				$_scoreinfo = @unserialize($rt['content']);
				$result['scoreinfo'] = $_scoreinfo;
				$result['total'] = $_scoreinfo['totalEvaluation'];
				$result['hid']	= $rt['hid'];
				$result['hname'] = $rt['hname'];
				$result['ctime'] = get_date($rt['ctime']);
			}
		}
		return $result;
	}
	
	/**
	 * @param $hid	楼盘ID
	 * @param $content	楼盘内容
	 * 		  array('typekey' => array('score','added'))
	 * @param $total	综合评价	
	 * @param $userdefined	用户自定义显示评分人数
	 * @return null
	 */
	function insertScoreInfoByHid($hid,$content,$total='',$userdefined='-1'){
		if ($hid) {
			$scoreinfo = $_content = array();
			$_sql = "SELECT * FROM ".$this->_tablename." c WHERE c.ctype=".pwEscape($this->_ctype['score'])." AND c.hid=".pwEscape($hid);
			$rt = $this->_db->get_one($_sql);
			if ($rt) {
				$_content = @unserialize($rt['content']);
			}
			$scoreinfo = $this->_setScoreInfo($content,$_content,$userdefined);
			if ($userdefined != '-1') {
				$scoreinfo['totalEvaluation'] = $total;
			} else {
				$_content && $scoreinfo['totalEvaluation'] = $_content['totalEvaluation'];
			}
			$defindAverageScore = $scoreinfo['defindAverageScore'];
			$scoreinfo = @serialize($scoreinfo);
			$_insert = array(
				'hid'		=>  $hid,
				'ctime'		=>  $this->timestamp,
				'ctype'		=>  $this->_ctype['score'],
				'content'	=>	$scoreinfo,
			);
			if ($rt) {
				$_sql = "UPDATE ".$this->_tablename." SET ".pwSqlSingle($_insert)." WHERE ctype=".pwEscape($this->_ctype['score']);
			}else{
				$_sql = "INSERT INTO ".$this->_tablename." SET ".pwSqlSingle($_insert);
			}
			$this->_db->update($_sql);
			$this->updateHouseEvaluationsScoreByHid($hid,$defindAverageScore);
		}
	}
	
	/**
	 * 计算楼盘评分详细信息
	 * 评分信息存储结构
	 * array(
	 *		"actCount"				=>  '', 
	 *		"defindCount"			=>  1234, 
	 *		"actAverageScore"		=>  64, 
	 *		"defindAverageScore"	=>  67, 
	 *		"totalEvaluation"		=>  "44444444444", 
	 *		"1"						=>  array ( "act"	=>  83, 	"def"	=>  17 ), 
	 *		"2"						=>  array ( "act"	=>  49, 	"def"	=>  0  ), 
	 *		"3"						=>  array ( "act"	=>  49, 	"def"	=>  0  ), 
	 *		"4"						=>  array ( "act"	=>  40, 	"def"	=>  0  ), 
	 *		"5"						=>  array ( "act"	=>  101,	"def"	=>  0  ), 
	 * );
	 * @param $scores		本次评分信息
	 * 		  array('typekey' => array('score','added'))
	 * @param $content  	历史评分记录
	 * @param $userdefined	用户自定义显示评分人数
	 * @return array
	 */
	function _setScoreInfo($scores,$content,$userdefined=-1){
		$scoreinfo = array();
		if (is_array($scores) && !empty($scores)) {
			!$content && $content = array();
			if ($this->house_score) {
				$scoreinfo['actCount'] = $userdefined == -1 ? (int)$content['actCount'] + 1 : (int)$content['actCount'];
				$scoreinfo['defindCount'] = $userdefined == -1 ?  (int)$content['defindCount'] : (int)$userdefined;
				$_totalScore = $_totalScore_add = $_count = 0;
				
				foreach ($scores as $key => $value) {
					if (array_key_exists($key,$this->house_score)) {
						if ($content[$key]) {
							$_added = isset($value[1]) ? (int)$value[1] : (int)$content[$key]['def'];
							$_score = (int)$value[0] ? $this->_getAverageScore((int)$content[$key]['act'],(int)$value[0],$scoreinfo['actCount']) : (int)$content[$key]['act'];	// (int)$content[$key]['actually'] + (int)$value[0];
						} else {
							$_added = (int)$value[1];
							$_score = (int)$value[0];
						}
						$_added = ($_score + $_added) > $this->fullScore ? ($this->fullScore-$_score) : $_added;
						$_totalScore_add += $_score + $_added;
						$_totalScore += $_score;
						$_count++;
						$scoreinfo[$key] = array('act' => $_score, 'def' => $_added );
					}
				}
				
				if ($_totalScore != 0 && $_count != 0) {
					$scoreinfo['actAverageScore'] = floor($_totalScore/$_count);
				}else{
					$scoreinfo['actAverageScore'] = 0;
				}
				if ($_totalScore_add != 0 && $_count != 0) {
					$scoreinfo['defindAverageScore'] = floor($_totalScore_add/$_count);
				}else{
					$scoreinfo['defindAverageScore'] = 0;
				}
			}
		}else{
			$scoreinfo = $content;
		}
		return $scoreinfo;
	}
	
	/**
	 * @param $old
	 * @param $new
	 * @param $count
	 * @return unknown_type
	 */
	function _getAverageScore($old,$new,$count){
		$result = 0;
		if ($count) {
			$count = (int)$count;
			$result = ceil($old*(($count-1)/$count) + $new/$count);
		}
		return $result;
	}
	
	
	//用户最后评分信息
	/**
	 * @param $data
	 * @return unknown_type
	 */
	function replaceUserScore($data){
		if (is_array($data) && !empty($data)) {
			$_sql = "REPLACE INTO pw_house_userscore (hid,uid,stime,content) VALUES ".pwSqlMulti($data);
			$this->_db->update($_sql);
		}
	}
	
	/**
	 * @return unknown_type
	 */
	function clearUserScore($hid='',$uid=''){
		global $timestamp;
		$_where = '';
		if ($hid != '') {
			$_where .= " AND hid=".pwEscape($hid);
		}
		if ($uid != '') {
			$_where .= " AND uid=".pwEscape($uid);
		}
		$_sql = "DELETE FROM pw_house_userscore WHERE stime <= ".pwEscape($timestamp)." $_where ";
		$this->_db->update($_sql);
	}
	
	/**
	 * @param $uid
	 * @param $hid
	 * @return unknown_type
	 */
	function getUserScoreByUidHid($uid,$hid){
		$result = array();
		$_sql = "SELECT h.* FROM pw_house_userscore h WHERE h.hid=".pwEscape($hid)." AND h.uid=".pwEscape($uid);
		$result = $this->_db->get_one($_sql);
		return $result;
	}
	
}
?>